package com.denghq.projectbuilder.component.web.Filter;

import com.denghq.projectbuilder.common.util.DateUtils;
import com.denghq.projectbuilder.common.util.UUIDUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class NoCacheResourceFilter implements Filter {


    private static final String[] NO_CACHE_PATH = {"/index.html","/"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String servletPath = request.getServletPath();
        if(NO_CACHE_PATH != null && NO_CACHE_PATH.length > 0){
            for (String path : NO_CACHE_PATH) {
                if(path.equals(servletPath)){
                    // 不缓存的请求头
                    String dateStr = DateUtils.format(new Date(), "yyyyMMddHHmmss");
                    response.setHeader("Date", dateStr);
                    response.setHeader("Last-Modified", dateStr);
                    response.setHeader("Cache-Control", "no-cache");
                    response.setHeader("ETag", UUIDUtils.getUUID());
                    response.setHeader("Expires","0");
                }
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
